var express = require('express');
var path = require('path'); //路径模块
var favicon = require('serve-favicon');
var logger = require('morgan');
// var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// var session = require('express-session');

const index = require('./server/routers/index');
const thai = require('./server/routers/thai');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'dist'));//模版文件所在目录

app.engine('html', require('ejs').renderFile); //html作为页面渲染引擎
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

// app.use(cookieParser('yezigd.com')); //引入cookie
// app.use(session({
//   secret: 'yezigd.com',
//   resave: true,
//   saveUninitialized: true,
//   cookie: {
//     maxAge: 60 * 1000 * 60 * 12
//   }
// }));

app.use(express.static(path.join(__dirname, 'dist'))); //静态资源文件

app.use('/', index);
app.use('/thai', thai);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


//错误处理需要放在最后
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {err}
  });
});

app.use(function errorHandler(err, req, res, next) {
  if (res.headersSent) {
    return next(err);
  }
  res.status(500);
  res.render('error', { error: err });
});

module.exports = app;
